package com.soft.collateral.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soft.collateral.entity.Agencies;
import com.soft.collateral.entity.User;
import com.soft.collateral.exception.CollateralException;
import com.soft.collateral.mapper.AgenciesMapper;
import com.soft.collateral.service.AgenciesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soft.collateral.vo.PageQueryVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 外估机构表 服务实现类
 * </p>
 *
 * @author liubin
 * @since 2025-07-25
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class AgenciesServiceImpl extends ServiceImpl<AgenciesMapper, Agencies> implements AgenciesService {

    private final AgenciesMapper agenciesMapper;

    /**
     * 分页查询外估机构
     * @param vo
     * @return
     */
    @Transactional(readOnly = true)
    @Override
    public Page<Agencies> page(PageQueryVO vo) {

        if(ObjectUtils.isEmpty(vo)){
            return null;
        }

        //1.封装分页对象
        Page<Agencies> page = Page.of(vo.getCurrentPage(), vo.getPageSize());
        LambdaQueryWrapper<Agencies> wrapper = new LambdaQueryWrapper<>();

        // 按机构名模糊查询
        wrapper.like(StringUtils.hasLength(vo.getQueryString()), Agencies::getName, vo.getQueryString());

        return agenciesMapper.selectPage(page, wrapper);
    }

    /**
     * 重写save方法保证名称唯一
     * @param agencies
     * @return
     */
    @Transactional
    @Override
    public boolean saveAgencies(Agencies agencies) {
        // 检查重复（以name为例）
        if (this.lambdaQuery()
                .eq(Agencies::getName, agencies.getName())
                .exists()) {
            throw new CollateralException("当前机构已存在!");
        }
        return this.save(agencies);
    }
}
